/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\QuotaManage\StockCheck\QuatoDetail\StockCheckModalDistributor.tsx
 * @Date: 2022-05-24 17:06:09
 * @LastEditTime: 2023-04-29 00:25:39
 */

import {
  columnRenders,
  http,
  IUdColumn,
  IUdDetailItem,
  UdDetail,
  UdDrawer,
  UdForm,
  UdModal,
  UdPageHeader,
  UdTable,
  UdToolbar,
} from '@/lib'
import React, { Component, createRef } from 'react'
import todoApi from '@/apis/TodoList/index'
import apis from '@/apis/AboutQuota'
import { Button, message, Modal, Upload } from 'antd'
import './approve.scss'
import QuotaApprove from '@/components/getQuotaApprove'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import ossService from '@/utils/OSS-upload/ossService'
import ossClientCreator from '@/utils/OSS-upload/ossClientCreator'
import { UploadFile } from 'antd/lib/upload/interface'
import UploadImgButton from '@/components/UploadImgButton'
import PhotoView from '@/components/PhotoViewSimple'
import AddMaterialModal from './AddMaterialModal'
import { unionBy } from 'lodash'
import EditStockCheckDistributor from './EditStockCheckDistributor'
import dayjs from 'dayjs'
const confirm = Modal.confirm
type IProps = {
  detailDataSource: Record<string, any>
  todoType?: any
  refresh?: (param) => void
}

type IState = {
  dataSource: Record<string, any>[]
  checkPerson: any[]
  workFlowList: any[]
  fileList: any[]
  visible: boolean
  previewImage: string
  loading: boolean
}

export default class StockCheckModalDistributor extends Component<IProps, IState> {
  private client
  private labelCol: any = { span: 4 }
  private form: WrappedFormUtils
  public cRef = createRef<any>()
  private detailItem: IUdDetailItem<any>[] = [
    {
      title: '客户名称',
      dataIndex: 'dealerName',
    },
    {
      title: '销售组织',
      dataIndex: 'brandName',
    },
    {
      title: '盘点周期',
      dataIndex: 'cycleText',
    },
  ]
  private columns: IUdColumn<any>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '50px',
      render: (text, reoled, index) => index + 1,
    },
    { title: '物料编号', dataIndex: 'prodBarcode', key: 'prodBarcode', minWidth: '140px' },
    { title: '物料名称', dataIndex: 'matName', key: 'matName', minWidth: '140px' },
    { title: '当前库存/件', dataIndex: 'nowRealStock', key: 'nowRealStock', minWidth: '140px' },
    { title: '当前动销/件', dataIndex: 'nowMove', key: 'nowMove', minWidth: '140px' },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right' as 'right',
      width: 160,
      render: columnRenders.operate([
        {
          title: '移除',
          action: (text: any, record: any) => {
            confirm({
              title: '确定要删除该物料吗?',
              onOk: () => {
                this.setState(preState => ({
                  dataSource: preState.dataSource.filter(item => item.prodBarcode !== record.prodBarcode),
                }))
              },
            })
          },
        },
        {
          title: '盘点',
          action: (text: any, record: any) => {
            this.handEditStockCheck(record)
          },
        },
      ]),
    },
  ]
  state: IState = {
    dataSource: [],
    checkPerson: [],
    workFlowList: [],
    fileList: [],
    visible: false,
    previewImage: '',
    loading: false,
  }

  async componentDidMount() {
    this.getWorkFlow()
    this.getUnionTableData()
    const config = await ossService.getOssConfig()
    this.client = ossClientCreator(config)
  }

  private handEditStockCheck = record => {
    let { detailDataSource: { record: { parentCode } } = {} } = this.props
    record['beginningRealStock'] = record['beginningRealStock']
    let { detailDataSource, detailDataSource: { brandCode, dealerCode, inventoryBegineTime, inventoryEndTime } = {} } =
      this.props
    UdDrawer.open({
      title: `库存盘点`,
      width: '60%',
      content: (
        <EditStockCheckDistributor
          orderParams={{
            parentCode,
            ErpCode: dealerCode,
            CorporationCode: brandCode,
            matCode: record.prodBarcode,
            StartDate: inventoryBegineTime,
            EndDate: inventoryEndTime,
          }}
          record={record}
          editTableData={this.editTableData}
          detailDataSource={detailDataSource}
        />
      ),
    })
  }

  private editTableData = record => {
    let {
      beginningRealStock,
      nowAog,
      allocateNumber,
      nowRealStock,
      onOrder,
      nowMove,
      nextMonthOrderNum,
      remark,
      nowMoveDes,
    } = record
    let { dataSource } = this.state
    for (let item of dataSource) {
      if (item.prodBarcode === record.prodBarcode) {
        Object.assign(item, {
          beginningRealStock,
          nowAog,
          allocateNumber,
          nowRealStock,
          onOrder,
          nowMove,
          nextMonthOrderNum,
          remark,
          nowMoveDes,
        })
        break
      }
    }
    this.setState({ dataSource })
  }

  //获取审批角色
  private getWorkFlow = () => {
    let { detailDataSource: { brandCode } = {} } = this.props
    http.get(todoApi.NextApproverRoleList, { params: { brandCode } }).then(res => {
      const { data } = res
      this.setState({ workFlowList: data })
    })
  }

  //选择审批人
  private handShowQuotaApprove(index) {
    this.cRef.current.handelCeck(index)
  }

  private handGetPerson(value) {
    this.setState({ checkPerson: value })
  }

  private getUnionTableData = async () => {
    this.setState({ loading: true })
    try {
      let { detailDataSource: { tradeCode } = {} } = this.props
      let tableData = []
      let preTableData = []
      tableData = await this.getTableData()
      tradeCode && (preTableData = await this.getPreTableData())
      const dataSource = unionBy(preTableData, tableData, 'prodBarcode')
      this.setState({ dataSource, loading: false })
    } catch (e) {
      this.setState({ loading: false })
      console.error(e)
    }
  }

  private getPreTableData = (): Promise<any> => {
    let { detailDataSource: { tradeCode } = {} } = this.props
    return http
      .post(apis.getMyAllmatByDealer, {
        tradeCode,
      })
      .then(res => {
        let { data: dataSource = [] } = res
        for (let item of dataSource) {
          item?.nowRealStock ?? (item.nowRealStock = null)
          item?.quotaCountNum ?? (item.quotaCountNum = null)
          item?.onOrder ?? (item.onOrder = null)
          item.nowMove =
            +item.beginningRealStock + +item.nowAog + +item.allocateNumber - +item.nowRealStock - +item.onOrder
        }
        return dataSource
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private getTableData = (): Promise<any> => {
    let {
      detailDataSource: {
        record: { parentCode },
        agentType,
        brandCode,
        dealerCode,
        inventoryBegineTime,
        inventoryEndTime,
      } = {},
    } = this.props
    return http
      .post(apis.GetAllmatByDealer, {
        parentCode,
        agentType,
        brandCode,
        dealerCode,
        inventoryEndTime,
        inventoryBegineTime,
      })
      .then(res => {
        let { data: dataSource = [] } = res
        for (let item of dataSource) {
          item?.nowRealStock ?? (item.nowRealStock = null)
          item?.quotaCountNum ?? (item.quotaCountNum = null)
          item?.onOrder ?? (item.onOrder = null)
          item.nowMove =
            +item.beginningRealStock + +item.nowAog + +item.allocateNumber - +item.nowRealStock - +item.onOrder
        }
        return dataSource
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private onOk = e => {
    let { dataSource, fileList, checkPerson } = this.state
    let {
      detailDataSource: { brandCode, dealerCode, brandName, dealerName, inventoryBegineTime, inventoryEndTime } = {},
      refresh,
      todoType,
    } = this.props
    let length = dataSource?.length ?? 0
    if (length === 0) {
      message.warn('盘点物料不能为空')
      return
    }
    for (let i = 0; i < length; i++) {
      if (!Number.isFinite(dataSource[i]['beginningRealStock'])) {
        message.warn(`物料【${dataSource[i].matName}】期初库存字段未填写`)
        return false
      }
      if (!Number.isFinite(dataSource[i]['nowAog'])) {
        message.warn(`物料【${dataSource[i].matName}】期间开单字段未填写`)
        return false
      }
      // if (!Number.isFinite(dataSource[i]['allocateNumber'])) {
      //   message.warn(`物料【${dataSource[i].matName}】调入调出字段未填写`)
      //   return false
      // }
      if (!Number.isFinite(dataSource[i]['nowRealStock'])) {
        message.warn(`物料【${dataSource[i].matName}】当前实物库存字段未填写`)
        return false
      }
      if (!Number.isFinite(dataSource[i]['onOrder'])) {
        message.warn(`物料【${dataSource[i].matName}】当前未到货字段未填写`)
        return false
      }
      if (!Number.isFinite(dataSource[i]['nowMove'])) {
        message.warn(`物料【${dataSource[i].matName}】期间动销数字段未填写`)
        return false
      }
    }
    if (checkPerson.length === 0) {
      message.warn('请选择审批人')
      return
    }
    e.drawerBtnLoading()
    let { detailDataSource: { record } = {} } = this.props
    const stockSaveReq = [
      {
        parentCode: record.parentCode,
        parentName: record.parentName,
        brandCode,
        brandName,
        dealerCode,
        dealerName,
        dataSource: 'SALESMAN',
        checkStockSaveDetailReqVos: dataSource,
        stockCertificate: fileList.map(item => item.url).toString(),
        workflowReqVos: {
          name: 'candidateUsers',
          userId: [checkPerson[0].id],
        },
        description: dayjs().format('YYYY年-MM月'),
        inventoryBegineTime,
        inventoryEndTime,
      },
    ]
    http
      .post(apis.CheckStockSave, stockSaveReq)
      .then(res => {
        if (res.data === true) {
          message.success('操作成功')
          e.close()
          //盘点重发要刷新
          refresh?.(todoType)
        } else {
          message.error('操作失败')
          e.drawerBtnLoadingHide()
        }
      })
      .catch(() => {
        e.drawerBtnLoadingHide()
      })
  }

  private handCustomRequest = (e: any) => {
    if (!this.client) return
    ossService.put(this.client, 'settled-review/annex', e.file).then((url: any) => {
      let index = this.state.fileList.findIndex((n: UploadFile) => n.uid === e.file.uid)
      if (index > -1) {
        let newFileList: UploadFile[] = [...this.state.fileList]
        Object.assign(newFileList[index], { url, status: 'done' })
        this.setState({ fileList: newFileList })
        // this.state.fileList[index].url = url
        // this.state.fileList[index].status = 'done'
      } else {
        this.state.fileList.push({
          ...e.file,
          status: 'done',
          url: url,
        })
      }
      this.setState({
        fileList: this.state.fileList,
      })
    })
  }

  private handleRemove = e => {
    let { uid } = e
    this.setState(preState => {
      return { fileList: preState.fileList.filter(item => item.uid !== uid) }
    })
  }

  private handPreview = file => {
    this.setState({ visible: true, previewImage: file.url })
  }

  private handAddMaterialModal = () => {
    let { dataSource } = this.state
    let {
      detailDataSource: { brandCode, dealerCode, inventoryBegineTime, inventoryEndTime },
    } = this.props
    UdModal.open({
      title: '添加盘点物料',
      width: '50%',
      content: (
        <AddMaterialModal
          inventoryBegineTime={inventoryBegineTime}
          inventoryEndTime={inventoryEndTime}
          brandCode={brandCode}
          dealerCode={dealerCode}
        />
      ),
      onOk: value => {
        console.log('value', value)
        let materialDataSource: Record<string, any>[] = [...value]
        for (let item of materialDataSource) {
          item?.nowRealStock ?? (item.nowRealStock = null)
          item?.quotaCountNum ?? (item.quotaCountNum = null)
          item?.onOrder ?? (item.onOrder = null)
          item.nowMove =
            +item.beginningRealStock + +item.nowAog + +item.allocateNumber - +item.nowRealStock - +item.onOrder
        }
        const unionDataSource: any[] = unionBy([...dataSource, ...materialDataSource], 'prodBarcode')
        //! 此处应该合并去重
        Array.isArray(materialDataSource) &&
          materialDataSource.length > 0 &&
          this.setState({ dataSource: unionDataSource })
      },
    })
  }

  render() {
    let { dataSource, fileList, visible, previewImage, loading } = this.state
    let { detailDataSource } = this.props
    return (
      <>
        {/* <UdPageHeader title="库存盘点" /> */}
        <UdDetail items={this.detailItem} dataSource={detailDataSource} />
        <UdToolbar
          other={
            <Button type="primary" onClick={this.handAddMaterialModal}>
              添加物料
            </Button>
          }
        ></UdToolbar>
        <UdTable rowKey="prodBarcode" columns={this.columns} dataSource={dataSource} loading={loading}></UdTable>
        <h4 style={{ marginTop: 10 }}>凭证附件</h4>
        <div style={{ height: '130px', overflow: 'hidden' }}>
          <Upload
            customRequest={this.handCustomRequest}
            accept="image/*"
            listType="picture-card"
            fileList={fileList}
            onRemove={this.handleRemove}
            onPreview={this.handPreview}
            multiple={true}
          >
            <UploadImgButton />
          </Upload>
        </div>
        <Modal
          visible={visible}
          footer={null}
          onCancel={() => {
            this.setState({ visible: false })
          }}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
        <h4 style={{ marginTop: 10 }}>审批流程</h4>
        <div className="approve-wrap">
          <div className="node-name-wrap">
            <div className="approve-title">节点名称：</div>
            <span className="circle-point"></span>
            <div>{this.state.workFlowList[0]?.nodeName || '暂无流程模板'}</div>
          </div>
          <div className="person-name-wrap">
            <div className="approve-title">审批人:</div>
            <div
              className={this.state.checkPerson[0]?.realName ? 'add-plus-name' : 'add-plus'}
              onClick={() => {
                this.state.workFlowList[0] ? this.handShowQuotaApprove(0) : (() => {})()
              }}
            >
              {this.state.checkPerson[0]?.realName || '+'}
            </div>
          </div>
        </div>
        <QuotaApprove
          handCilck={this.handGetPerson.bind(this)}
          cRef={this.cRef}
          ids={this.state.workFlowList[0]?.roleIds}
        />
      </>
    )
  }
}
